'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { createPortal } from 'react-dom';
import { usePersonas } from '@/lib/hooks/usePersonas';
import { useCreateSession } from '@/lib/hooks/useCreateSession';
import { SkillSelector } from './SkillSelector';
import { PersonaCard } from './PersonaCard';
import { LoadingSpinner } from '@/components/ui/LoadingSpinner';
import { EmptyState } from '@/components/ui/EmptyState';

interface PersonaModalProps {
  isOpen: boolean;
  onClose: () => void;
}

export function PersonaModal({ isOpen, onClose }: PersonaModalProps) {
  const { data: personas, loading, error } = usePersonas();
  const { run, loading: creating } = useCreateSession();
  const [selectedSkill, setSelectedSkill] = useState<string>("socratic_tutor");
  const router = useRouter();

  async function handleCreate(personaId: string, skills: string[]) {
    const skill = skills.includes(selectedSkill) ? selectedSkill : skills[0];
    const res = await run({ personaId, skill });
    onClose(); // Close modal
    router.push(`/sessions/${res.sessionId}`);
  }

  if (!isOpen) return null;

  const modalContent = (
    <div className="fixed inset-0 z-[9999] overflow-y-auto">
      {/* Background */}
      <div 
        className="fixed inset-0 bg-black bg-opacity-50 transition-opacity"
        onClick={onClose}
      />
      
      {/* Modal */}
      <div className="flex min-h-full items-center justify-center p-4">
        <div className="relative w-full max-w-4xl transform overflow-hidden rounded-2xl bg-white shadow-xl transition-all">
          {/* Header */}
          <div className="border-b border-gray-200 px-6 py-5 bg-gradient-to-r from-blue-50/50 to-indigo-50/50">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3 min-w-0 flex-1">
                <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-xl flex items-center justify-center shadow-sm flex-shrink-0">
                  <svg className="w-5 h-5 text-white" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M18 10c0 3.866-3.582 7-8 7a8.841 8.841 0 01-4.083-.98L2 17l1.338-3.123C2.493 12.767 2 11.434 2 10c0-3.866 3.582-7 8-7s8 3.134 8 7zM7 9H5v2h2V9zm8 0h-2v2h2V9zM9 9h2v2H9V9z" clipRule="evenodd" />
                  </svg>
                </div>
                <div className="min-w-0 flex-1">
                  <h2 className="text-xl font-semibold text-gray-900">Select Chat Persona</h2>
                  <p className="text-sm text-gray-600 mt-1">Select an AI persona to start a new conversation</p>
                </div>
              </div>
              <button
                onClick={onClose}
                className="rounded-xl p-2.5 text-gray-400 hover:bg-white/80 hover:text-gray-600 transition-colors shadow-sm flex-shrink-0"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
          </div>

          {/* Content */}
          <div className="px-6 py-5 max-h-[70vh] overflow-y-auto">
            {/* Skill selector */}
            <div className="mb-6">
              <SkillSelector
                selectedSkill={selectedSkill}
                onSkillChange={setSelectedSkill}
              />
            </div>

            {/* Persona grid */}
            {loading ? (
              <div className="flex items-center justify-center py-12">
                <div className="flex items-center gap-3">
                  <LoadingSpinner size="lg" />
                  <span className="text-base text-gray-600">Loading personas...</span>
                </div>
              </div>
            ) : error ? (
              <EmptyState
                icon={
                  <svg className="h-12 w-12" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
                  </svg>
                }
                title="Loading failed"
                description={error}
              />
            ) : personas.length === 0 ? (
              <EmptyState
                icon={
                  <svg className="h-12 w-12" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                  </svg>
                }
                title="No available personas"
                description="No AI personas are currently available, please try again later"
              />
            ) : (
              <div className="grid grid-cols-1 gap-4 lg:gap-6 sm:grid-cols-2 lg:grid-cols-3">
                {personas.map((persona) => (
                  <PersonaCard
                    key={persona.id}
                    persona={persona}
                    selectedSkill={selectedSkill}
                    onSkillChange={setSelectedSkill}
                    onCreateSession={handleCreate}
                    isCreating={creating}
                  />
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );

  // Use Portal to render to body
  if (typeof window !== 'undefined') {
    return createPortal(modalContent, document.body);
  }

  return null;
}